import React, { useState, useCallback } from 'react';
import { useSelector } from 'react-redux';
import { Button, Modal, Card, Row, Col, Typography, message, Input } from 'antd';
import { PlusOutlined, FileTextOutlined, VideoCameraOutlined, AudioOutlined } from '@ant-design/icons';
import { Track } from '@/store/tracksTypes';
import { addTrack } from '@/services/track';
import { TrackType } from '@/services/track/types';
import { RootState } from '@/store';
import { eventBus } from '@/utils';
import './AddTracks.css';
import { nanoid } from '@reduxjs/toolkit';

const { Title, Text } = Typography;
interface TrackTypeOption {
    type: Track['type'];
    title: string;
    description: string;
    icon: React.ReactNode;
    color: string;
    backendType: TrackType; // 对应后端的轨道类型
}

const AddTracks: React.FC = () => {
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [selectedTrackType, setSelectedTrackType] = useState<Track['type'] | null>(null);
    const [trackName, setTrackName] = useState('');
    // 从Redux store获取当前草稿ID
    const currentDraftId = useSelector((state: RootState) => state.drafts.draftId);
    // 轨道类型选项配置
    const trackTypeOptions: TrackTypeOption[] = [
        {
            type: 'text',
            title: '文本',
            description: '添加文字、标题、字幕等文本内容',
            icon: <FileTextOutlined style={{ fontSize: '24px' }} />,
            color: '#1890ff',
            backendType: TrackType.TEXT,
        },
        {
            type: 'sticker',
            title: '图片',
            description: '添加图片、贴纸、图标等视觉元素',
            icon: <VideoCameraOutlined style={{ fontSize: '24px' }} />,
            color: '#52c41a',
            backendType: TrackType.VIDEO,
        },
        {
            type: 'video',
            title: '视频',
            description: '添加视频片段、动画等视频内容',
            icon: <VideoCameraOutlined style={{ fontSize: '24px' }} />,
            color: '#722ed1',
            backendType: TrackType.VIDEO,
        },
        {
            type: 'audio',
            title: '音频',
            description: '添加背景音乐、音效、旁白等音频内容',
            icon: <AudioOutlined style={{ fontSize: '24px' }} />,
            color: '#fa8c16',
            backendType: TrackType.AUDIO,
        },
    ];

    // 显示模态框
    const showModal = useCallback(() => {
        setIsModalVisible(true);
        setSelectedTrackType(null);
        setTrackName('');
    }, []);

    // 隐藏模态框
    const handleCancel = useCallback(() => {
        setIsModalVisible(false);
        setSelectedTrackType(null);
        setTrackName('');
    }, []);

    // 生成轨道名称：片段类型+UUID
    const generateTrackName = useCallback((trackType: Track['type']) => {
        const typeNames = {
            text: '文本',
            sticker: '图片',
            video: '视频',
            audio: '音频',
            background: '背景',
        };
        const typeName = typeNames[trackType] || '轨道';
        const uuid = nanoid(8); // 生成8位随机ID
        return `${typeName}_${uuid}`;
    }, []);

    // 选择轨道类型
    const handleSelectTrackType = useCallback(
        (trackType: Track['type']) => {
            setSelectedTrackType(trackType);
            // 生成轨道名称
            const trackName = generateTrackName(trackType);
            setTrackName(trackName);
        },
        [generateTrackName]
    );

    // 确认添加轨道
    const handleConfirm = useCallback(async () => {
        if (!selectedTrackType) return;
        if (!trackName.trim()) {
            message.error('请输入轨道名称');
            return;
        }
        if (!currentDraftId) {
            message.error('未找到当前草稿ID，请重新加载页面');
            return;
        }
        const selectedOption = trackTypeOptions.find((option) => option.type === selectedTrackType);
        if (!selectedOption) return;
        try {
            // 构建后端需要的结构
            const trackInfo = {
                draft_id: currentDraftId,
                track_type: selectedOption.backendType,
                track_name: trackName.trim(),
                mute: selectedOption.type === 'audio' ? false : undefined, // 音频轨道默认不静音
                relative_index: 0,
            };
            // 提前关闭弹窗并更新UI，给用户更好的体验
            setIsModalVisible(false);
            setSelectedTrackType(null);
            setTrackName('');
            // 发布添加轨道更新UI事件
            eventBus.emit('track:added:ui', {
                id: nanoid(),
                type: trackInfo.track_type,
            });
            // 调用后端API创建轨道
            const response = await addTrack(trackInfo);
            if (response.data) {
                // 使用事件总线发布抓取草稿事件
                eventBus.emit('draft:updated', { draftId: currentDraftId });
                message.success(`${trackName}创建成功`);
            }
        } catch (error: any) {
            console.error('创建轨道失败:', error);
            const errorMessage = error?.response?.data?.message || error?.message || '创建轨道失败，请重试';
            message.error(errorMessage);
        }
    }, [selectedTrackType, trackName, trackTypeOptions, currentDraftId]);

    return (
        <div className="add-tracks-container">
            <Button type="primary" size="large" icon={<PlusOutlined />} onClick={showModal} className="add-tracks-button">
                添加轨道
            </Button>
            <Modal
                title="选择轨道类型"
                open={isModalVisible}
                onCancel={handleCancel}
                onOk={handleConfirm}
                okText="确定"
                cancelText="取消"
                width={600}
                okButtonProps={{
                    disabled: !selectedTrackType || !trackName.trim(),
                }}
                className="add-tracks-modal"
                zIndex={9999}
            >
                <div className="track-type-selection">
                    <Row gutter={[16, 16]}>
                        {trackTypeOptions.map((option) => (
                            <Col span={12} key={option.type}>
                                <Card
                                    hoverable
                                    className={`track-type-card ${selectedTrackType === option.type ? 'selected' : ''}`}
                                    onClick={() => handleSelectTrackType(option.type)}
                                    style={{
                                        borderColor: selectedTrackType === option.type ? option.color : undefined,
                                    }}
                                >
                                    <div className="track-type-content">
                                        <div className="track-type-icon" style={{ color: option.color }}>
                                            {option.icon}
                                        </div>
                                        <div className="track-type-info">
                                            <Title level={5} style={{ margin: 0, marginBottom: '4px' }}>
                                                {option.title}
                                            </Title>
                                            <Text type="secondary" style={{ fontSize: '12px' }}>
                                                {option.description}
                                            </Text>
                                        </div>
                                    </div>
                                </Card>
                            </Col>
                        ))}
                    </Row>
                </div>
                {selectedTrackType && (
                    <div className="track-name-input" style={{ marginTop: '24px' }}>
                        <Title level={5} style={{ marginBottom: '12px', color: 'white' }}>
                            轨道名称
                        </Title>
                        <Input placeholder="请输入轨道名称" value={trackName} onChange={(e) => setTrackName(e.target.value)} maxLength={50} showCount />
                    </div>
                )}
            </Modal>
        </div>
    );
};

export default AddTracks;
